<?php

namespace app\purchase\controller;

use app\purchase\model\Accessory;
use app\purchase\model\Clientbill;
use app\purchase\model\OrderAccessory;
use app\purchase\model\OrderBill;
use app\purchase\model\OrderGoods;
use app\purchase\model\OrderLog;
use function Sodium\add;
use think\Db;
use think\Request;
use think\Exception;
use app\purchase\model\Order as OrderModel;
use app\purchase\model\Cart as CartModel;
use app\purchase\model\Goods as GoodsModel;
use  app\purchase\model\Clientbill as InvoiceModel;
use app\purchase\model\OrderGoods as OrderGoodsModel;
use app\purchase\model\OrderAddress as OrderAddressModel;
use app\purchase\model\OrderLog as OrderLogModel;
use app\purchase\model\OrderAction as OrderActionModel;
use app\purchase\model\ClientAddress as ClientAddressModel;

class Order extends \PurchaseController
{
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */


    public function save(Request $request)
    {

        $post = $request->param();

        $post['client_id'] = \request()->header('company');

        $login_user_id = \request()->header('userId');

        $orderModel = new OrderModel();
        $Clients = new Client();
        $aNameData = $Clients->getName($post['client_id']);

        $Staff = new \app\crm\model\Staff();
        $staff_name = $Staff->where('staff_id',$login_user_id)->value('staff_name');

        try {
            Db::startTrans();
            // 添加订单信息
            $AddOrade = [];
            $snModel = new \app\purchase\model\Sn();
            $sn =  $snModel->getSn('OH-',1);

            $AddOrade['order_sn'] = 'DH-O-'.date('Ymd').'-'.$sn[0];
            $AddOrade['delivery_time'] = strtotime($post['delivery_time']);
            $AddOrade['client_id'] =$post['client_id'];
            $AddOrade['bill_message'] = $post['bill_message'];
            $AddOrade['is_discount'] = $post['is_discount'];
            $AddOrade['order_des'] = $post['order_des'];
            $AddOrade['discount_price'] = $post['discount_price'];
            $AddOrade['order_time'] = strtotime(date('Y-m-d H:i:s'));
            $AddOrade['make'] = $staff_name;
            $AddOrade['type'] = 0;
            $OrderModel = new OrderModel();
            $orderDb = $OrderModel->orderDb();
            $OrderId = $orderDb->insertGetId($AddOrade);

            $searchGoods = '';
            $numHe = 0;
            $pNum = 0;
            //商品数据
            $addGoods = [];
            //商品搜索组装
            $GoodsModel = new GoodsModel;
            $OrderGoodsModel = new OrderGoodsModel();
                foreach ($post['goods'] as $goodsK => $goodsV){

                    $goods_Data = $GoodsModel->gIdAndUnitPrice($goodsV['goods_id'],$goodsV['unit_id'], $post['client_id']);
                    $addGoods['order_id'] = $OrderId;
                    $addGoods['goods_id'] = $goods_Data['goods_id'];
                    $addGoods['goods_img'] = $goods_Data['goods_img'];
                    $addGoods['goods_name'] = $goods_Data['goods_name'];
                    $addGoods['goods_num'] = $goodsV['quantity'];
                    $addGoods['unit_id'] = $goodsV['unit_id'];
                    $addGoods['goods_sn'] = $goodsV['goods_sn'];
                    $addGoods['goods_price'] = $goods_Data['price'];
                    $m1 = '';
                    $m2 = '';
                    $m3 = '';
                    if(!empty($goods_Data['specification1_name'])&&!empty($goods_Data['specification1_value'])){
                        $m1 = ':';
                    }
                    if(!empty($goods_Data['specification2_name'])&&!empty($goods_Data['specification2_value'])){
                        $m2 = ':';
                    }
                    if(!empty($goods_Data['specification3_name'])&&!empty($goods_Data['specification3_value'])){
                        $m3 = ':';
                    }
                    $addGoods['goods_type'] = $goods_Data['specification1_name'].$m1.$goods_Data['specification1_value'].'    '.$goods_Data['specification2_name'].$m2.$goods_Data['specification2_value'].'    '.$goods_Data['specification3_name'].$m3.$goods_Data['specification3_value'];

                    $addGoods['goods_subtotal'] =$goods_Data['price']*$goodsV['quantity'];
                    $addGoods['order_goods_des'] = isset($goodsV['brief']) ? $goodsV['brief'] : '';
                    $pNum += $addGoods['goods_subtotal'] ;
                    $numHe += $addGoods['goods_num'];
                    $searchGoods.=$goods_Data['goods_name'].'|'.$goods_Data['goods_sn'].'|'.$goods_Data['keywords'];

                    $OrderGoodsModel->insert($addGoods);
                }

            $uData['search_goods']=$searchGoods;
            $uData['num']=$numHe;
            $uData['price']=$pNum;
            $orderDb->where('order_id',$OrderId)->update($uData);
            //订单地址记录
            $ClientAddress = new \app\shop\model\ClientAddress();
            $ClientAddressDb = $ClientAddress->ClientAddressDb();
            $ClientAddressData = $ClientAddressDb->where('client_address_id',$post['address_id'])->find();
            $orderAddress['order_id'] = $OrderId;
            $orderAddress['area'] = $ClientAddressData['area'];
            $orderAddress['phone'] = $ClientAddressData['phone'];
            $orderAddress['mobile'] = $ClientAddressData['mobile'];
            $orderAddress['consignee'] = $ClientAddressData['consignee'];
            $orderAddress['address'] = $ClientAddressData['address'];
            $OrderAddressModel = new OrderAddressModel();
            $OrderAddressModel->insertGetId($orderAddress);

            // 开票信息
            if($post['bill_message']!=0){
                $ClientbillModel = new Clientbill();
                $ClientbillDb = $ClientbillModel->ClientbillDb();
                $invoice = $ClientbillDb->where('id',$post['invoice_id'])->find();
                $AddOradeBill['order_id'] = $OrderId;
                $AddOradeBill['invoice'] = $invoice['invoice'];
                $AddOradeBill['invoice_content'] = $invoice['invoice_content'];
                $AddOradeBill['tax_num'] = $invoice['tax_num'];
                $AddOradeBill['invoice_address'] = $invoice['invoice_address'];
                $AddOradeBill['invoice_mobile'] = $invoice['invoice_mobile'];
                $AddOradeBill['bank_name'] = $invoice['bank_name'];
                $AddOradeBill['bank'] = $invoice['bank'];
                $AddOradeBill['bank_account'] = $invoice['bank_account'];
                $OrderBillModel = new OrderBill();
                $OrderBillDb = $OrderBillModel->OrderBillDb();
                $OrderBillDb->insert($AddOradeBill);
            }

            //新增附件
            if(!empty($post['order_accessory'])){
                $order_accessory = $post['order_accessory'];
                $accessoryModel = new Accessory();
                $AccessoryDb = $accessoryModel->AccessoryDb();
                if(!empty($order_accessory)){
                    $OrderAccessoryModel = new OrderAccessory();
                    $OrderAccessoryDb = $OrderAccessoryModel->OrderAccessoryDb();
    
                    foreach ($order_accessory as $v1){
                        $arrAccessory = explode('|',$v1);
                        $aid = $AccessoryDb->insertGetId(['accessory_url'=>$arrAccessory[0],'accessory_name'=>$arrAccessory[1]]);
                        $addOrderAccessory['accessory_id'] = $aid;
                        $addOrderAccessory['order_id'] = $OrderId;
                        $OrderAccessoryDb->insert($addOrderAccessory);
    
    
                    }
                }
            }
            
            //添加日志
            $log = [
                'order_id'=>$OrderId,
                'operator'=>$staff_name,
                'company_name'=>$aNameData,
                'create_at'=>strtotime(date('Y-m-d H:i:s')),
                'action'=>'创建订货单',
                'desc'=>'已提交订货单，等待订货单审核'

            ];
            $OrderLog = new OrderLog();
            $OrderLog->add($log);
            //清空购物车
            $cartModel = new CartModel();
            $cartDb = $cartModel->cartDb();
            $userId = \request()->header('company');
            $cartDb->where([
                    'client_id' => $userId,
                ])->delete();
            Db::commit();

            $this->successTerminate($orderModel);
        } catch (Exception $e) {
            Db::rollback();

            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $orderModel = new OrderModel();

        try {
            $params = $request->param();
            $data = $orderModel->search($params);
            foreach($data['data'] as &$v){
                $v['order_time'] =date('Y-m-d H:i:s',$v['order_time']);
                $v['create_at'] =date('Y-m-d H:i:s',$v['create_at']);
                $v['type'] = $orderModel->getStatusTrans($v['type']);
                $v['gathering_type'] = $orderModel->getFinanceStatusTrans($v['gathering_type']);
                $v['warehouse_deliver'] = $orderModel->getWarehouseStatusTrans($v['out_warehouse']).'/'.$orderModel->getDeliverGoodsStatusTrans($v['deliver_goods']);
                unset($v['out_warehouse']);
                unset($v['deliver_goods']);

            }

            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }



    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        $orderModel = new OrderModel();

        try {

            $data = $orderModel->getOrderDetail($id);

            $this->successTerminate($data);

        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $orderModel = new OrderModel();

        try {

            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }


    /**
     * 批量删除
     */
    public function batchDel(Request $request){
        $orderModel = new OrderModel();
        
        try{

            $params = $request->post();
            
            $orderModel->where('order_id','in',$params['order_ids'])->delete();

            $this->successTerminate();

        }catch(Exception $e){
            
            $this->serverErrorTerminate($e->getMessage());

        }
    }

    /**
     * 批量审核
     */
    public function batchAudit(Request $request){
        try{

            $params = $request->post();
            
            $status = $params['status'];

            foreach ($params['order_ids'] as $id) {

                $orderModel = new OrderModel();

                $flag = $orderModel->where('order_id',$id)->value('status');

                if($flag == ($status - 1)){
                    $orderModel->where('order_id',$id)->update(['status'=>$status]);
                }

            }

            $this->successTerminate();

        }catch(Exception $e){
            
            $this->serverErrorTerminate($e->getMessage());

        }
    }

    /**
     * 修改订单主数据
     */
    public function updateInfo(Request $request){
        $post = $request->param();

        try{
            Db::startTrans();

            $login_user_id = \request()->header('userId');
            $company_id = \request()->header('company');

            $Staff = new \app\crm\model\Staff();
            $staff_name = $Staff->where('staff_id',$login_user_id)->value('staff_name');

            $Clients = new Client();
            $aNameData = $Clients->getName($company_id);

            $Order = new OrderModel();
            $OrderId = $post['order_id'];
            //$up['warehouse'] = $post['warehouse'];
            $up['order_des'] = $post['order_des'];

            $goods =  $post['goods'];
            if(!empty($post['order_accessory'])){
                $order_accessory = $post['order_accessory'];
            }
            $Order = new OrderModel();
            $orderDb = $Order->orderDb();


            $orderDb->where('order_id',$OrderId)->update($up);

            //订单地址记录


            $ClientAddress = new ClientAddressModel();
            $ClientAddressDb = $ClientAddress->ClientAddressDb();
            
            $ClientAddressData = $ClientAddressDb->where('client_address_id',$post['address_id'])->find();
            $orderAddress['order_id'] = $OrderId;
            $orderAddress['area'] = $ClientAddressData['area'];
            $orderAddress['phone'] = $ClientAddressData['phone'];
            $orderAddress['mobile'] = $ClientAddressData['mobile'];
            $orderAddress['consignee'] = $ClientAddressData['consignee'];
            $orderAddress['address'] = $ClientAddressData['address'];
            $orderAddress['save_time'] = strtotime(date('Y-m-d H:i:s'));

            $OrderAddressModel = new OrderAddressModel();
            $OrderAddressModel->insertGetId($orderAddress);

            //处理附件
            if(!empty($order_accessory)){
                $accessoryModel = new Accessory();
                $AccessoryDb = $accessoryModel->AccessoryDb();
                $OrderAccessoryModel = new OrderAccessory();
                $OrderAccessoryDb = $OrderAccessoryModel->OrderAccessoryDb();
                $OrderAccessoryDb->where('order_id',$OrderId)->delete();
               foreach ($order_accessory as $v1){
                    $arrAccessory = explode('|',$v1);

                    $aid = $AccessoryDb->insertGetId(['accessory_url'=>$arrAccessory[0],'accessory_name'=>$arrAccessory[1]]);
                    $addOrderAccessory['accessory_id'] = $aid;
                    $addOrderAccessory['order_id'] = $OrderId;
                    $OrderAccessoryDb->insert($addOrderAccessory);

                }
            }else{
                $OrderAccessoryModel = new OrderAccessory();
                $OrderAccessoryDb = $OrderAccessoryModel->OrderAccessoryDb();
                $OrderAccessoryDb->where('order_id',$OrderId)->delete();
            }

            $OrderGoods = new OrderGoods();
            $OrderGoodsDb =  $OrderGoods->OrderGoodsDb();
            foreach ($goods as $k=>$v){

                $OrderGoodsDb->where('id',$v['id'])->update(['order_goods_des'=>$v['order_goods_des']]);
            }
            $Order = new \app\shop\model\Order();
            $orderDb = $Order->orderDb();
            $orderDb->where('order_id',$OrderId)->update($up);
            //添加日志

            $log = [
                'operator'=>$staff_name,
                'company_name'=>$aNameData,
                'order_id'=>$OrderId,
                'create_at'=>strtotime(date('Y-m-d H:i:s')),
                'action'=>'修改订单主数据',
                'desc'=>'修改订单主数据'
            ];
            $OrderLog = new OrderLog();
            $OrderLog->add($log);
            Db::commit();

            $this->successTerminate();

        }catch(Exception $e){
            Db::rollback();

            $this->serverErrorTerminate($e->getMessage());

        }



    }
    /**
     * 修改订单商品数据
     */
    public function updateGoods(Request $request){
        $post = $request->param();
        try{
            Db::startTrans();
            $OrderId = $post['order_id'];
            $goods =  $post['goods'];
            $up['num'] = 0;
            $up['price'] = 0;
            $up['search_goods'] = '';
            $OrderGoods = new OrderGoods();
            $Goods = new \app\shop\model\Goods();
            $GoodsModel = $Goods->GoodsDb();
            $OrderGoodsDb =  $OrderGoods->OrderGoodsDb();
            foreach ($goods as $k=>$v){
                if($v['type']==1){ //修改
                    $up['price']+=$v['goods_subtotal'];
                    $up['num']+=$v['goods_num'];
                    $goods_Data = $GoodsModel->where('goods_id',$v['goods_id'])->find();
                    $v['goods_img'] = $goods_Data['goods_img'];
                    $v['goods_name'] = $goods_Data['goods_name'];
                    $v['goods_type'] = $goods_Data['specification1_name'].':'.$goods_Data['specification1_value'].'    '.$goods_Data['specification2_name'].':'.$goods_Data['specification2_value'].'    '.$goods_Data['specification3_name'].':'.$goods_Data['specification3_value'];
                    $up['search_goods'].=$goods_Data['goods_name'].'|'.$goods_Data['goods_sn'].'|'.$goods_Data['goods_code1'].'|'.$goods_Data['goods_code2'].'|'.$goods_Data['goods_code3'].'|'.$goods_Data['keywords'];
                    $OrderGoodsDb->where('id',$v['id'])->update($v);
                }
                else if ($v['type']==2){//新增
                    $up['price']+=$v['goods_subtotal'];
                    $up['num']+=$v['goods_num'];
                    $goods_Data = $GoodsModel->where('goods_id',$v['goods_id'])->find();
                    $v['order_id'] = $OrderId;
                    $v['goods_img'] = $goods_Data['goods_img'];
                    $v['goods_name'] = $goods_Data['goods_name'];
                    $v['goods_type'] = $goods_Data['specification1_name'].':'.$goods_Data['specification1_value'].'    '.$goods_Data['specification2_name'].':'.$goods_Data['specification2_value'].'    '.$goods_Data['specification3_name'].':'.$goods_Data['specification3_value'];
                    $up['search_goods'].=$goods_Data['goods_name'].'|'.$goods_Data['goods_sn'].'|'.$goods_Data['goods_code1'].'|'.$goods_Data['goods_code2'].'|'.$goods_Data['goods_code3'].'|'.$goods_Data['keywords'];
                    $OrderGoodsDb->insert($v);
                }
                else{
                    $OrderGoodsDb->where('id',$v['id'])->delete();
                }
            }
            $Order = new \app\shop\model\Order();
            $orderDb = $Order->orderDb();
            $orderDb->where('order_id',$OrderId)->update($up);
            $utid = \request()->header('userId');
            $Clients = new Client();
            $aNameData = $Clients->getName($utid);

            //添加日志
            $log = [
                'order_id'=>$OrderId,
                'operator'=>$aNameData,
                'company_name'=>$aNameData,
                'create_at'=>strtotime(date('Y-m-d H:i:s')),
                'action'=>'修改订单商品数据',
                'desc'=>'修改订单商品数据'
            ];
            $OrderLog = new OrderLog();
            $OrderLog->add($log);
            Db::commit();
            $this->successTerminate();

        }catch(Exception $e){
            Db::rollback();
            $this->serverErrorTerminate($e->getMessage());
        }

    }
    /**
     * 订单作废
     */
    public function cancellation(Request $request){
        try{
            $post = $request->param();
            $orderModel = new OrderModel();

            $orderModel->where('order_id',$post['id'])->update(['transaction_des'=>$post['transaction_des'],'type'=>6]);

//添加日志
            $utid = \request()->header('userId');
            $Clients = new Client();
            $aNameData = $Clients->getName($utid);

            $log = [
                'order_id'=>$post['id'],
                'operator'=>$aNameData,
                'company_name'=>$aNameData,
                'create_at'=>strtotime(date('Y-m-d H:i:s')),
                'action'=>'订单作废',
                'desc'=>'订单作废'
            ];
            $OrderLog = new OrderLog();
            $OrderLog->add($log);

            $this->successTerminate();

        }catch(Exception $e){

            $this->serverErrorTerminate($e->getMessage());

        }
    }
}
